package com.hoperun.nocserver.modules.base.service;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hoperun.nocserver.common.conf.RabbitMQConfig;
import com.rabbitmq.client.Channel;

@Component
public class MqService {

	private static final Log LOGGER = Logs.get();

	@Autowired
	RabbitTemplate rabbitTemplate;

	@Autowired
	ConnectionFactory connectionFactory;

	/**
	 * 设置mq发送体
	 * 
	 * @param content
	 * @return
	 */
	public Message setMqMsg(String content) {
		// 设置发送体头部
		return MessageBuilder.withBody(content.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
				.setContentEncoding("utf-8").setMessageId(UUID.randomUUID() + "").build();
	}

	/**
	 * 往mq指定队列发送数据
	 * 
	 * @param queue
	 *            队列名称
	 * @param content
	 *            消息文本
	 */
	public void convertAndSend(String queue, String content) {
		this.rabbitTemplate.convertAndSend(queue, setMqMsg(content));
	}

	/**
	 * 获取mq连接
	 * 
	 * @return mq连接
	 */
	public Connection getMqConn() {
		return connectionFactory.createConnection();
	}

	public Channel createChannel() {
		return getMqConn().createChannel(false);
	}

	/**
	 * 创建队列（默认绑定指定的交换机和路由）
	 * 
	 * @param queue
	 *            队列名称
	 */
	public void createQueue(String queue) {
		try {
			Channel channel = createChannel();
			channel.queueDeclare(queue, false, false, false, null);
			channel.queueBind(queue, RabbitMQConfig.EXCHANGE, RabbitMQConfig.ROUTINGKEY);
		} catch (IOException e) {
			LOGGER.error("创建队列or绑定队列失败！", e);
		}
	}

	/**
	 * 获取消息监听对象
	 * 
	 * @param queue
	 *            队列名称
	 * @return 消息监听对象
	 */
	public SimpleMessageListenerContainer getContainer(String queue) {
		SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
		container.setQueues(new Queue(queue));
		container.setExposeListenerChannel(true);
		// container.setMaxConcurrentConsumers(200);
		// container.setConcurrentConsumers(4);
		ExecutorService executorService = Executors.newFixedThreadPool(RabbitMQConfig.THREAD_POOL_SIZE);
		container.setTaskExecutor(executorService); // 设置确认模式手工确认
		container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
		return container;
	}

}
